from sqlalchemy import func

from appserver import db_store
from models.entity.model_base import ModelBase


class Alarm(ModelBase):
    __tablename__ = "alarms"
    __bind_key = "main"
    #{"Topic": "/1401010010001/M1304", "Type": 0, "Level": 0,
    # "Context": {"Msg": "超限报警,值500.上限450,下限330"},
     #"SerialId":"1538028110634","Time":"2018-09-27T14:01:50.634325+08:00"}
    id = db_store.Column(db_store.Integer, primary_key=True)
    topic = db_store.Column(db_store.String(255), comment=u"MQTT topic")
    type = db_store.Column(db_store.Integer, nullable=False)
    level = db_store.Column(db_store.Integer, nullable=False)
    context = db_store.Column(db_store.String(255), comment=u"内容")
    serial_id = db_store.Column(db_store.String(255), primary_key=True)
    time = db_store.Column(db_store.DateTime(), nullable=False)


    # grade = db_store.Column(db_store.Integer, nullable=False)
    # alarm_time = db_store.Column(db_store.DateTime(), nullable=False)
    # details = db_store.Column(db_store.String(128), nullable=False)
    # pump_name = db_store.Column(db_store.String(128), nullable=False)
    # device_name = db_store.Column(db_store.String(128), nullable=False)
    # monitoring = db_store.Column(db_store.String(128), nullable=False)
    # reference = db_store.Column(db_store.String(128), nullable=False)
    # type = db_store.Column(db_store.Integer, nullable=False)
    #
    #

    def __repr__(self):
        return "<Alarm %d>" % self.id

    def get_max_id(self):
        val = db_store.session.query(func.max(Alarm.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print("error is ")
            print(e)
            db_store.session.rollback()
            return False

    @staticmethod
    def get_alarm_by_id(id):
        return Alarm.query.filter_by(id=id).first()

    # # 以python字典的形式返回任务实例的字典
    # def get_dic(self):
    #     rdic = {}
    #     rdic['id'] = self.id
    #     rdic['grade'] = self.grade
    #     rdic['alarm_time'] = self.alarm_time
    #     rdic['details'] = self.details
    #     rdic['pump_name'] = self.pump_name
    #     # rdic['end_time'] = self.end_time.strftime("%Y-%m-%d %H:%M:%S")
    #     rdic['device_name'] = self.device_name
    #     rdic['monitoring'] = self.monitoring
    #     rdic['reference'] = self.reference
    #     rdic['type'] = self.type
    #
    #     return rdic